package com.jy.appmarket.cards;

import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.ViewToClickToExpand;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jy.app.market.idata.card.CardApkTop;
import com.jy.app.market.idata.data.Apk;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.activity.AppDetailActivity;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.download.DownloadItem;
import com.jy.appmarket.download.DownloadService;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.utils.IdataUtils;
import com.jy.appmarket.utils.LoadImageUtils;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.PackageUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 类说明：
 * 
 * @author Baker.li
 * @date 2015年8月21日
 * @version 1.0
 */

public class ApkTopUICard extends DownloadableUICard {
	private static final String TAG = ApkTopUICard.class.getSimpleName();
	private CardApkTop mApkTop;
	private Apk mApk;
	private DownloadItem mDownloadItem;
	private DownloadActivity mDLActivity;
	private String mdlId;
	private int mBlueTextColor;
	private int mOrangeTextColor;
	private int mGrayTextColor;
	private String mIconUrl;

	public ApkTopUICard(Context context, CardApkTop apkTop) {
		super(context, R.layout.app_top_card_layout);
		mApkTop = apkTop;
		if (mApkTop == null || mApkTop.getApk() == null) {
			return;
		}
		mApk = mApkTop.getApk();
		mdlId = DownloadUtils.generateDownloadId(mApk.getPackageName(), mApk.getVersionCode());
		mIconUrl = IdataUtils.getIconUrl(mApk.getIcons());
		mDLActivity = (DownloadActivity) context;
		init();
	}

	private void init() {
		mDownloadItem = mDLActivity.getDownloadById(mdlId);

		Resources r = getContext().getResources();
		mBlueTextColor = r.getColor(R.color.download_btn_blue_style_text);
		mOrangeTextColor = r.getColor(R.color.download_btn_orange_style_text);
		mGrayTextColor = r.getColor(R.color.download_btn_gray_style_text);

		// RelativeDownloadExpand rd = new RelativeDownloadExpand(getContext());
		// addCardExpand(rd);
		setOnClickListener(new OnCardClickListener() {
			@Override
			public void onClick(Card card, View view) {
				Intent detail = new Intent(mDLActivity, AppDetailActivity.class);
				detail.putExtra(AppDetailActivity.EXTRA_NAME, mApk.getTitle());
				detail.putExtra(AppDetailActivity.EXTRA_PKG, mApk.getPackageName());
				detail.putExtra(AppDetailActivity.EXTRA_SOURCE, ApkSource.toSourceString(getApkSource()));
				mDLActivity.startActivity(detail);
			}
		});

	}

	@Override
	public void setupInnerViewElements(ViewGroup parent, View view) {
		TextView download = parent.findViewById(R.id.app_top_card_download_button);
		ViewToClickToExpand viewToClickToExpand = ViewToClickToExpand.builder().enableForExpandAction();
		setViewToClickToExpand(viewToClickToExpand);

		download.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				int status = mDLActivity.getDownloadStatus(mdlId, mApk.getPackageName(), mApk.getVersionCode());

				switch (status) {
				case DownloadService.STATUS_INSTALLED: {
					try {
						Intent intent = getContext().getPackageManager()
								.getLaunchIntentForPackage(mApk.getPackageName());
						mDLActivity.startActivity(intent);
					} catch (Exception e) {
						e.printStackTrace();
						Toast.makeText(mDLActivity, "打开失败", Toast.LENGTH_SHORT).show();
					}
				}
					break;

				case DownloadService.STATUS_CAN_INSTALL:
					mDLActivity.installApk(mDownloadItem);
					break;
				case DownloadService.STATUS_DOWNLOADING:
					mDLActivity.stopDownload(mdlId);
					break;
				case DownloadService.STATUS_NO_STATUS: {
					mDLActivity.addDownload(mApk.getDownloadUrl().getUrl(), mApk.getTitle(), mApk.getPackageName(),
							mApk.getVersionName(), mApk.getVersionCode(), mApk.getMd5(), mIconUrl,
							ApkSource.toSourceString(getApkSource()));
					if (DownloadUtils.isMobileNetwork(mDLActivity)) {
						Toast.makeText(mDLActivity, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
					}
				}
					break;

				case DownloadService.STATUS_PAUSED_BY_ERROR:
				case DownloadService.STATUS_PAUSED_BY_MOBILE_NETWORK:
				case DownloadService.STATUS_PAUSED_BY_USER:
					mDLActivity.startDownload(mdlId);
					if (DownloadUtils.isMobileNetwork(mDLActivity)) {
						Toast.makeText(mDLActivity, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
					}
					break;
				case DownloadService.STATUS_PENDING:
					mDLActivity.stopDownload(mdlId);
					break;
				case DownloadService.STATUS_DOWNLOAD_OUT_OF_DATE: // 下载过期状态，强制处理为有更新状态，点击后重新开始下载
					// mDLActivity.removeDownloadImmediately(mdlId);
					// mDLActivity.removeDownloadFiles(mApk.getDownloadUrl().getUrl());

					mDLActivity.removeOutofDateDownloads(mApk.getPackageName());

					mDLActivity.addDownload(mApk.getDownloadUrl().getUrl(), mApk.getTitle(), mApk.getPackageName(),
							mApk.getVersionName(), mApk.getVersionCode(), mApk.getMd5(), mIconUrl,
							ApkSource.toSourceString(getApkSource()));

					if (DownloadUtils.isMobileNetwork(mDLActivity)) {
						Toast.makeText(mDLActivity, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
					}
					break;
				case DownloadService.STATUS_NEED_TO_UPDATE:
					mDLActivity.addDownload(mApk.getDownloadUrl().getUrl(), mApk.getTitle(), mApk.getPackageName(),
							mApk.getVersionName(), mApk.getVersionCode(), mApk.getMd5(), mIconUrl,
							ApkSource.toSourceString(getApkSource()));

					if (DownloadUtils.isMobileNetwork(mDLActivity)) {
						Toast.makeText(mDLActivity, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
					}
					break;

				default:
					break;
				}

			}
		});
		ImageView icon = parent.findViewById(R.id.app_top_card_icon);
		TextView name = parent.findViewById(R.id.app_top_card_name);
		TextView detail = parent.findViewById(R.id.app_top_card_desc);
		TextView top = parent.findViewById(R.id.app_top_card_top);
		name.setText((AppMarketApplication.showLocal & mApk.getLocal() > 0 ? "★" : "") + mApk.getTitle());

		// // detail.setText(Html.fromHtml(mApk.getDescription()));
		// detail.setText(mApk.getDescription());

		String detailStr = mApk.getRecommend();
		if (TextUtils.isEmpty(detailStr)) {
			detailStr = mApk.getTagline();
			if (TextUtils.isEmpty(detailStr)) {
				detailStr = mApk.getDescription();
			}
		}
		detail.setText(Html.fromHtml(detailStr));

		ImageLoader.getInstance().displayImage(mIconUrl, icon, LoadImageUtils.getListIconDisplayOption(mDLActivity));

		switch (mApkTop.getTop()) {
		case 1:
			// top.setBackgroundResource(R.drawable.top_num_1_background);
			top.setTextColor(0xfff53a05);
			break;
		case 2:
			// top.setBackgroundResource(R.drawable.top_num_2_background);
			top.setTextColor(0xfffa8a00);
			break;
		case 3:
			// top.setBackgroundResource(R.drawable.top_num_3_background);
			top.setTextColor(0xfff7c600);
			break;
		default:
			// top.setBackgroundResource(R.drawable.top_num_others_background);
			top.setTextColor(0xffb2b2b2);
			break;
		}
		top.setText(String.valueOf(mApkTop.getTop()) + ".");
		setupViews(parent);
	}

	@Override
	public int getType() {
		return 3;
	}

	@Override
	public void onPackageInstalled(String pkgName) {
		if (pkgName.equals(mApk.getPackageName())) {
			refreshList(getIndex());
		}
	}

	@Override
	public void onPackageUninstalled(String pkgName) {
		if (pkgName.equals(mApk.getPackageName())) {
			refreshList(getIndex());
		}
	}

	@Override
	public void onDownloadCreated(DownloadItem di) {
		if (!di.getId().equals(mdlId)) {
			return;
		}
		mDownloadItem = di;
		refreshList(getIndex());
		// LogUtil.d(TAG, "onDownloadCreated:" + di.getName());

	}

	@Override
	public void onDownloadRemoved(String id) {
		if (!id.equals(mdlId)) {
			return;
		}
		mDownloadItem = null;
		refreshList(getIndex());
		// LogUtil.d(TAG, "onDownloadRemoved:" + id);
	}

	@Override
	public void onDownloadChanged(DownloadItem di) {
		if (di == null || !mdlId.equals(di.getId())) {
			return;
		}
		mDownloadItem = di;
		refreshList(getIndex());
	}

	@Override
	public void onProgressChanged(String id, long downloaded, long speed) {
		if (!id.equals(mdlId)) {
			return;
		}
		if (mDownloadItem == null) {
			return;
		}
		mDownloadItem.setDownloadedSize(downloaded);
		mDownloadItem.setSpeed(speed);
		refreshList(getIndex());
	}

	private void setupViews(View parent) {
		TextView info = parent.findViewById(R.id.app_top_card_info);
		TextView progressStatus = parent.findViewById(R.id.app_top_card_statuswithprogress);
		ProgressBar progress = parent.findViewById(R.id.app_top_card_progressbar);
		TextView button = parent.findViewById(R.id.app_top_card_download_button);
		TextView progressSize = parent.findViewById(R.id.app_top_card_statuswithsize);
		View progressLayoutView = parent.findViewById(R.id.app_top_card_progress_layout);

		String infoText = mApk.getInstalledCountStr() + "人安装  "
				+ Formatter.formatFileSize(getContext(), safeInt(mApk.getBytes()));

		Drawable drawableLeft = getContext().getResources().getDrawable(R.drawable.download_info);
		int status = mDLActivity.getDownloadStatus(mdlId, mApk.getPackageName(), mApk.getVersionCode());
		switch (status) {
		case DownloadService.STATUS_CAN_INSTALL:
			info.setVisibility(View.VISIBLE);
			progressLayoutView.setVisibility(View.GONE);

			info.setText(R.string.wait_for_install);
			info.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
			button.setBackgroundResource(R.drawable.download_button_blue);
			button.setTextColor(mBlueTextColor);
			button.setText(R.string.install);
			button.setClickable(true);
			break;

		case DownloadService.STATUS_PAUSED_BY_ERROR:
			info.setVisibility(View.GONE);
			progressLayoutView.setVisibility(View.VISIBLE);

			progressStatus.setText(R.string.download_error);
			progressSize.setText(getProgressString(mDownloadItem, mApk, mdlId));
			progress.setIndeterminate(false);
			progress.setProgress(getProgress(mDownloadItem, mApk, mdlId));

			button.setTextColor(mOrangeTextColor);
			button.setBackgroundResource(R.drawable.download_button_orange);
			button.setText(R.string.retry);
			button.setClickable(true);

			break;
		case DownloadService.STATUS_INSTALLED:
			info.setVisibility(View.VISIBLE);
			progressLayoutView.setVisibility(View.GONE);

			info.setText(infoText);
			info.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
			button.setTextColor(mGrayTextColor);
			button.setBackgroundResource(R.drawable.download_button_gray);
			button.setText(R.string.open);
			button.setClickable(true);
			break;
		case DownloadService.STATUS_NO_STATUS:
			info.setVisibility(View.VISIBLE);
			progressLayoutView.setVisibility(View.GONE);

			info.setText(infoText);
			info.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
			button.setTextColor(mBlueTextColor);
			button.setBackgroundResource(R.drawable.download_button_blue);
			button.setText(R.string.download);
			button.setClickable(true);
			break;
		case DownloadService.STATUS_PAUSED_BY_MOBILE_NETWORK:
			info.setVisibility(View.GONE);
			progressLayoutView.setVisibility(View.VISIBLE);

			progressStatus.setText(R.string.wait_for_wifi);
			progressSize.setText(getProgressString(mDownloadItem, mApk, mdlId));
			progress.setIndeterminate(false);
			progress.setProgress(getProgress(mDownloadItem, mApk, mdlId));

			button.setTextColor(mBlueTextColor);
			button.setBackgroundResource(R.drawable.download_button_blue);
			button.setText(R.string.go_on);
			button.setClickable(true);

			break;
		case DownloadService.STATUS_PAUSED_BY_USER:
			info.setVisibility(View.GONE);
			progressLayoutView.setVisibility(View.VISIBLE);

			progressStatus.setText(R.string.pause);
			progressSize.setText(getProgressString(mDownloadItem, mApk, mdlId));
			progress.setIndeterminate(false);
			progress.setProgress(getProgress(mDownloadItem, mApk, mdlId));

			button.setTextColor(mBlueTextColor);
			button.setBackgroundResource(R.drawable.download_button_blue);
			button.setText(R.string.go_on);
			button.setClickable(true);

			break;
		case DownloadService.STATUS_DOWNLOADING:
			info.setVisibility(View.GONE);
			progressLayoutView.setVisibility(View.VISIBLE);

			progressStatus.setText(getSpeedString(mDownloadItem));
			progressSize.setText(getProgressString(mDownloadItem, mApk, mdlId));
			progress.setIndeterminate(false);
			progress.setProgress(getProgress(mDownloadItem, mApk, mdlId));

			button.setTextColor(mGrayTextColor);
			button.setBackgroundResource(R.drawable.download_button_gray);
			button.setText(R.string.pause);
			button.setClickable(true);

			break;

		case DownloadService.STATUS_PREPARE_TO_DOWNLOAD:
			info.setVisibility(View.GONE);
			progressLayoutView.setVisibility(View.VISIBLE);

			progressStatus.setText(R.string.prepare_download);
			progressSize.setText(getProgressString(mDownloadItem, mApk, mdlId));
			progress.setIndeterminate(true);

			button.setTextColor(mGrayTextColor);
			button.setBackgroundResource(R.drawable.download_button_gray);
			button.setText(R.string.pause);
			button.setClickable(false);

			break;
		case DownloadService.STATUS_PREPARE_TO_STOP:
			info.setVisibility(View.GONE);
			progressLayoutView.setVisibility(View.VISIBLE);

			progressStatus.setText("0K/S");
			progressSize.setText(getProgressString(mDownloadItem, mApk, mdlId));
			progress.setIndeterminate(true);

			button.setTextColor(mBlueTextColor);
			button.setBackgroundResource(R.drawable.download_button_gray);
			button.setText(R.string.go_on);
			button.setClickable(false);

			break;
		case DownloadService.STATUS_INSTALLING:
			info.setVisibility(View.GONE);
			progressLayoutView.setVisibility(View.VISIBLE);

			progressStatus.setText(R.string.installing);
			progressSize.setText("");
			progress.setIndeterminate(true);

			button.setTextColor(mBlueTextColor);
			button.setBackgroundResource(R.drawable.download_button_gray);
			button.setText(R.string.installing);
			button.setClickable(false);
			break;

		case DownloadService.STATUS_PENDING:
			info.setVisibility(View.GONE);
			progressLayoutView.setVisibility(View.VISIBLE);

			progressStatus.setText(R.string.waiting);
			progressSize.setText(getSpeedString(mDownloadItem));
			progress.setIndeterminate(false);
			progress.setProgress(getProgress(mDownloadItem, mApk, mdlId));

			button.setTextColor(mGrayTextColor);
			button.setBackgroundResource(R.drawable.download_button_gray);
			button.setText(R.string.waiting);
			button.setClickable(true);

			break;
		case DownloadService.STATUS_DOWNLOAD_OUT_OF_DATE: // 下载过期状态，强制处理为有更新状态，点击后重新开始下载
			info.setVisibility(View.VISIBLE);
			progressLayoutView.setVisibility(View.GONE);

			info.setText(infoText);
			info.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
			button.setTextColor(mBlueTextColor);
			button.setBackgroundResource(R.drawable.download_button_blue);
			button.setClickable(true);

			if (PackageUtils.isPackageInstalled(mDLActivity, mApk.getPackageName())) {
				button.setText(R.string.update);
			} else {
				button.setText(R.string.download);
			}
			break;
		case DownloadService.STATUS_NEED_TO_UPDATE:
			info.setVisibility(View.VISIBLE);
			progressLayoutView.setVisibility(View.GONE);

			info.setText(infoText);
			info.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
			button.setTextColor(mBlueTextColor);
			button.setBackgroundResource(R.drawable.download_button_blue);
			button.setText(R.string.update);
			button.setClickable(true);
			break;
		default:
			LogUtil.w(TAG, "unknown status:" + status);
			break;
		}
	}
}